import {
    ProjectGetXMLFiles,
    ProjectGetImageFiles,
    ProjectGetCurrentId,
    ProjectUpdateFile,
    ProjectRemoveFile,
    ProjectCreateXMLView,
} from "./ProjectMange.js";
import {
    API_UploadImages,
    API_GetFile,
    API_GetImageUrl,
    API_RenameFile,
} from "./api.js";
import { Login_GetStatus, Login_GetToken } from "./login.js";
import { POPMenuObject } from "./POPMenu.js";
import { Mask_Hide, Mask_Show } from "./Mask.js";

class FileMange {
    parent = null;
    onTabSelectd = null;
    onFileSelectd = null;
    onContextmenu = null;
    files = [];
    fileType = "view";
    constructor(id) {
        this.fileList = [];

        this.parent = document.getElementById(id);
        if (this.parent) {
            this.parent.innerHTML = this.html();
            this.fileListDiv = document.getElementById("filelist");
            this.fileMangeTabSelect =
                document.getElementById("filemangeTabSelect");

            this.fileMangeTabSelect.addEventListener("click", (e) => {
                if (e.target.classList.contains("filemangeTabButton")) {
                    const buttons = this.fileMangeTabSelect.querySelectorAll(
                        ".filemangeTabButton"
                    );
                    buttons.forEach((button) => {
                        button.classList.remove("fileTabSeletd");
                    });
                    e.target.classList.add("fileTabSeletd");

                    if (this.onTabSelectd) {
                        const type = e.target.getAttribute("type");
                        // console.log(e.target);
                        this.fileType = type;
                        this.onTabSelectd(type);
                    }
                }
            });

            let selectedFiles = [];
            document
                .getElementById("imageUpload")
                .addEventListener("change", function (e) {
                    selectedFiles = Array.from(e.target.files);
                    // fileCountSpan.textContent = selectedFiles.length;

                    console.log(selectedFiles);
                    if (selectedFiles.length === 0) {
                        return;
                    }

                    API_UploadImages(
                        Login_GetToken(),
                        ProjectGetCurrentId(),
                        selectedFiles,
                        (res) => {
                            console.log("上传结果:", res);
                            if (res.code === 0) {
                                ProjectUpdateFile(() => {
                                    FileMangeUpdate();
                                });
                            } else {
                                alert("上传失败: " + res.msg);
                            }
                        }
                    );
                });

            this.fileListDiv.addEventListener("click", (e) => {
                if (this.fileType === "image") {
                    if (Login_GetStatus() === 0) {
                        return;
                    }
                    document.getElementById("imageUpload").click();
                }
            });

            this.fileListDiv.addEventListener("contextmenu", (e) => {
                e.preventDefault();
                if (this.onContextmenu) {
                    this.onContextmenu(this.fileType, e);
                }
            });
        }
    }

    setFileList(files) {
        this.fileList = files;
        this.fileListDiv.innerHTML = "";
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            // const fileName = file.name;
            const fileItem = this.fileItem(file, this.fileType);
            // this.fileListDiv.innerHTML += fileItem;
            this.fileListDiv.appendChild(fileItem);
            fileItem.addEventListener("click", (e) => {
                const type = e.currentTarget.getAttribute("type");
                const id = e.currentTarget.getAttribute("file_id");
                const path = e.currentTarget.getAttribute("path");
                const name = e.currentTarget.getAttribute("title");
                if (this.onFileSelectd) {
                    this.onFileSelectd(type, id, path, name);
                }
            });
            fileItem.addEventListener("contextmenu", (e) => {
                e.preventDefault();
                const type = e.currentTarget.getAttribute("type");
                const id = e.currentTarget.getAttribute("file_id");
                const path = e.currentTarget.getAttribute("path");
                const name = e.currentTarget.getAttribute("title");
                console.log("右键菜单", type, id, path, name);
                const popMenu = POPMenuObject();
                popMenu.clear();
                popMenu.addItem("删除", { type: "delete", file_id: id }, () => {
                    if (Login_GetStatus() === 0) {
                        return;
                    }
                    if (!confirm("确定要删除这个文件吗？")) {
                        return;
                    }
                    ProjectRemoveFile(id, () => {
                        FileMangeUpdate();
                        // maskClose();
                        Mask_Hide();
                    });
                });
                popMenu.addItem(
                    "重命名",
                    { type: "rename", file_id: id },
                    () => {
                        const newName = prompt("请输入新的文件名", name);
                        if (newName && newName !== name) {
                            API_RenameFile(
                                Login_GetToken(),
                                id,
                                newName,
                                (res) => {
                                    if (res.code === 0) {
                                        ProjectUpdateFile(() => {
                                            FileMangeUpdate();
                                            Mask_Hide();
                                        });
                                    } else {
                                        alert("重命名失败: " + res.msg);
                                    }
                                }
                            );
                        }
                    }
                );
                // openMask();
                popMenu.show(e.clientX, e.clientY);
                Mask_Show(() => {
                    popMenu.hide();
                });
            });
        }
    }

    update() {
        console.log(type);
    }

    fileItem(fileInfo, fileType) {
        let html = "";

        let div = document.createElement("div");
        div.setAttribute("class", "fileitem");
        div.setAttribute("file_id", fileInfo.id);
        div.setAttribute("type", fileType);
        div.setAttribute("title", fileInfo.name);
        div.setAttribute("path", fileInfo.relative);

        if (fileType == "image") {
            //<span class="iconfont" style="font-size: 36px; margin-top: 5px;">&#xe62c;</span>
            html =
                `
                    <div class="fileImgBox">
                        <img src="` +
                API_GetImageUrl(Login_GetToken(), fileInfo.id) +
                `" alt="${fileInfo.name}" />
                    </div>
                    <div class="filename">${fileInfo.name}</div>
                `;
        } else {
            html = `
                    <div class="fileImgBox">
                        <span class="iconfont" style="font-size: 36px;">&#xe624;</span>
                    </div>
                    <div class="filename">${fileInfo.name}</div>
                `;
        }
        div.innerHTML = html;
        return div;
    }

    html() {
        return `<div style="width: 100%; height: calc(100% - 0px);">
                <input type="file" id="imageUpload" accept="image/jpeg, image/png" multiple style="display: none;" />
                <div id="filemange">
                    <div id="filelist">
                    
                    </div>
                    <div id="filemangeTabSelect">
                        <div class="filemangeTabButton fileTabSeletd" type="view"><span class="iconfont">&#xe6b5;</span>视图</div>
                        <div class="filemangeTabButton" type="image"><span class="iconfont">&#xe62c;</span>图片</div>

                    </div>
                </div>
            </div>`;
        // <div class="filemangeTabButton" type="script"><span class="iconfont">&#xe6bb;</span>脚本</div>
        // <div class="filemangeTabButton" type="sound"><span class="iconfont">&#xe645;</span>音频</div>
    }

    addFile(file) {}

    removeFile(file) {
        const index = this.fileList.indexOf(file);
        if (index > -1) {
            this.fileList.splice(index, 1);
        }
    }

    getFiles() {
        return this.fileList;
    }
}

var fileMange = null;
var fileMangeCurrentViewPath = "";
var fileMangeCurrentFileId = 0;

export function FileInit() {
    fileMange = new FileMange("bottomContent");
    fileMange.onTabSelectd = (tab) => {
        console.log("Tab selected:", tab);
        // fileMange.setFileList(getFileList(tab));
        if (tab === "view") {
            fileMange.setFileList(ProjectGetXMLFiles());
        } else if (tab === "image") {
            fileMange.setFileList(ProjectGetImageFiles());
        }
    };

    fileMange.onFileSelectd = (type, id, path, name) => {
        console.log("File selected:", type, path, name);
        if (type === "view") {
            if (fileMangeCurrentViewPath === path) {
                return;
            }
            API_GetFile(Login_GetToken(), id, (res) => {
                window["layout"].loadXML(res);
                document.getElementById("informationBar").innerText = name;
                fileMangeCurrentViewPath = path;
                fileMangeCurrentFileId = id;
            });
        }
    };
    fileMange.onContextmenu = (type, e) => {
        // console.log("Contextmenu:", type, e.target);

        const element = e.target;
        if (element.getAttribute("id") == "filelist" && type === "view") {
            const popMenu = POPMenuObject();
            popMenu.clear();
            popMenu.addItem("新建视图", null, () => {
                // document.getElementById("imageUpload").click();
                ProjectCreateXMLView();
                // popMenu.hide();
                Mask_Hide();
            });
            popMenu.show(e.clientX, e.clientY);
            Mask_Show(() => {
                popMenu.hide();
            });
        }
    };
}

export function FileMangeGetCurrentFileId() {
    return fileMangeCurrentFileId;
}
export function FileMangeGetCurrentViewPath() {
    return fileMangeCurrentViewPath;
}

export function FileMangeSetCurrentFileId(id) {
    fileMangeCurrentFileId = id;
}

export function FileMangeSetCurrentViewPath(path) {
    fileMangeCurrentViewPath = path;
}

export function FileMangeUpdate() {
    if (fileMange.fileType === "view") {
        fileMange.setFileList(ProjectGetXMLFiles());
    } else if (fileMange.fileType === "image") {
        fileMange.setFileList(ProjectGetImageFiles());
    }
}
